package com.ruoyi.oar.api.util;

import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class JsonUtil<psvm> {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
        // 过滤map中的null值
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true);
    }


    /**
     * 对象转json
     *
     * @param object
     * @return
     */
    public static String bean2json(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * json转对应类型的对象
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2bean(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将对象转化为特定的Bean.实际上是将obj转成json字符串,再将字符串转成指定bean
     */
    public static <T> T obj2bean(Object obj, Class<T> clazz) {
        if (obj == null) {
            return null;
        } else {
            String json = bean2json(obj);
            return json2bean(json, clazz);
        }
    }


    /**
     * 快捷：json转map
     *
     * @param json
     * @return
     */
    public static Map json2map(String json) {
        return json2bean(json, Map.class);
    }


    /**
     * 快捷：json转list
     *
     * @param json
     * @return
     */
    public static List json2list(String json) {
        return json2bean(json, List.class);
    }


    /**
     * list循环处理回调接口
     */
    @Deprecated
    public interface ListCallback {
        /**
         * 回调方法
         *
         * @param json list节点json字符串
         */
        void callback(String json);
    }


    public static void main(String[] args) {

        List list = new ArrayList();
        Map map = new HashMap();
        map.put("aa", "111");
        map.put("bb", null);

        list.add(map);
        System.out.println(JsonUtil.bean2json(map));
    }

}
